<?php

/**
 * Doctrine auth adapter
 *
 * @author     Mon Zafra <monzee at gmail>
 * @copyright  (c)2009 Mon Zafra
 * @category   Mz
 * @package    modules
 * @subpackage admin
 * @license    http://mz-project.googlecode.com/svn/trunk/LICENSE    MIT License
 * @version    SVN: $Id: Doctrine.php 47 2009-05-28 17:56:56Z monzee $
 */
class Admin_Model_Auth_Doctrine implements Zend_Auth_Adapter_Interface
{
    /**
     * constructor
     *
     * @param string $username
     * @param string $password  Should be hashed already
     */
    public function __construct($username, $password)
    {
        $this->_username = $username;
        $this->_password = $password;
    }

    public function authenticate()
    {
        $q = Doctrine_Query::create();
        $q->from('Admin_Model_Doctrine_User u')
          ->leftJoin('u.Roles r')
          ->select('u.id, u.username, u.password, r.id')
          ->where('u.username = ?', $this->_username);
        $user = $q->fetchOne(null, Doctrine::HYDRATE_ARRAY);

        if (false !== $user) {
            if ($user['password'] == $this->_password) {
                return new Zend_Auth_Result(
                    Zend_Auth_Result::SUCCESS,
                    $this->_createIdentity($user),
                    array('Authentication successful.')
                );
            } else {
                return new Zend_Auth_Result(
                    Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
                    $this->_username,
                    array('Invalid password.')
                );
            }
        } else {
            return new Zend_Auth_Result(
                Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
                $this->_username,
                array('No such user.')
            );
        }
    }

    protected function _createIdentity($user)
    {
        $userRoles = $user['Roles'];
        $user['roles'] = array();
        foreach ($userRoles as $role) {
            $user['roles'][] = $role['id'];
        }
        unset($user['password'], $user['Roles']);
        return new Admin_Model_Auth_Identity($user);
    }

}